import { DingTalk } from 'all-pusher-api/dist/DingTalk.js';
import { notificationConfig } from '../config/index.js';
import { logInfo, logWarn, logError } from '../logger.js';

export class NotificationService {
  constructor(config) {
    this.enabled = notificationConfig.enabled;
    if (this.enabled) {
      this.dingtalk = new DingTalk({
        token: config.dingtalk?.token,
        secret: config.dingtalk?.secret
      });
    }
  }

  async sendDingTalkMessage(message) {
    logInfo('发送钉钉消息: ' + JSON.stringify(message));

    // 检查全局通知开关
    if (!this.enabled) {
      logWarn('通知功能已禁用，跳过发送钉钉消息');
      return false;
    }

    if (!this.dingtalk) {
      logWarn('钉钉通知服务未初始化，跳过发送消息');
      return false;
    }

    const result = await this.dingtalk.send(message);

    if (result.status === 200) {
      logInfo('钉钉消息发送成功');
      return true;
    } else {
      logError('钉钉消息发送失败');
      return false;
    }
  }

  async sendShipmentReport(reports) {
    let catchBool = false;
    let text = '#### 物流详情\n';
    
    reports.forEach(item => {
      for (const key in item) {
        if (Object.prototype.hasOwnProperty.call(item, key)) {
          const val = item[key];
          text += `${key}: ${val}`;
          text += '\t\n';
          //判断 val 是否为数字
          if (!isNaN(val)) {
            if (val > 0) {
              catchBool = true;
            }
          }
        }
      }
      text += '\n';
    });
    
    text += '\n';
    if (catchBool) {
      text += `!!! warning\n有异常，请及时处理！`;
    } else {
      text += '无异常';
    }
    logInfo('物流报告内容: ' + text);

    return await this.sendDingTalkMessage({
      customOptions: {
        "msgtype": "markdown",
        "markdown": {
          "title": "物流详情",
          "text": text,
        }
      }
    });
  }
}